package com.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.common.R;
import com.springboot.pojo.Category;
import com.springboot.pojo.Dish;
import com.springboot.pojo.DishDto;
import com.springboot.pojo.DishFlavor;
import com.springboot.service.CategoryService;
import com.springboot.service.DishFlavorService;
import com.springboot.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishFlavorController {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
 @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
     log.info("save dishDto:{}",dishDto);
     dishService.saveWithFlavors(dishDto);
     //清理redis缓存
     String key="dish_"+ dishDto.getCategoryId()+"_1";
     redisTemplate.delete(key);
     return R.success("新增菜品成功");
 }
 @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
     //创建分页构造器
     Page<Dish> page02=new Page<>(page,pageSize);
     Page<DishDto> page03=new Page<>();
     //创建条件构造器
     LambdaQueryWrapper<Dish> lambdaQueryWrapper=new LambdaQueryWrapper();
     lambdaQueryWrapper.like(name!=null,Dish::getName,name);
     //添加排序
     lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
     //分页查询
     dishService.page(page02,lambdaQueryWrapper);
     //对象拷贝,不拷贝records属性
     BeanUtils.copyProperties(page02,page03,"records");
     //获取菜品对象集合
     List<Dish> records = page02.getRecords();
     //Stream流遍历处理数据
            List<DishDto> dishDtos =records.stream().map((item)->{
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //根据categoryId获取菜品分类对象
            Category byId = categoryService.getById(categoryId);
            //根据菜品分类对象获取分类名称
            String categoryName = byId.getName();
             dishDto.setCategoryName(categoryName);
              return dishDto;
        }).collect(Collectors.toList());
      page03.setRecords(dishDtos);
     return R.success(page03);
 }

    /**
     * 根据ID回显增加菜品页面基本信息
     * @param id
     * @return
     */
 @GetMapping("/{id}")
  public R<DishDto> get(@PathVariable Long id){
     DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
     return R.success(byIdWithFlavor);
  }
@PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info("save dishDto:{}",dishDto);
        dishService.updateWithFlavor(dishDto);

        return R.success("修改菜品成功");
    }

//    /**
//     * 根据条件查询菜品列表
//     * @param dish
//     * @return
//     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        //构造条件查询器
//        LambdaQueryWrapper<Dish> wrapper=new LambdaQueryWrapper();
//        wrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        //添加查询条件状态码等于1的启售状态
//        wrapper.eq(Dish::getStatus,1);
//        //添加排序条件
//        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(wrapper);
//        return R.success(list);
//    }


    /**
     * 根据条件查询菜品列表
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList =null;
        //动态构造key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();//dish_223443222234442212_1
        //先从redis中获取数据，
        dishDtoList  =(List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果有，则直接返回
        if (dishDtoList!=null){
            return R.success(dishDtoList);
        }
        //如果没有，则从数据库中查询
        //构造条件查询器
        LambdaQueryWrapper<Dish> wrapper=new LambdaQueryWrapper();
        wrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加查询条件状态码等于1的启售状态
        wrapper.eq(Dish::getStatus,1);
        //添加排序条件
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(wrapper);

           dishDtoList =list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                dishDto.setCategoryName(category.getName());
            }

            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> wrapper1=new LambdaQueryWrapper<>();
            wrapper1.eq(DishFlavor::getDishId,id);
            List<DishFlavor> flavorlist = dishFlavorService.list(wrapper1);
            dishDto.setFlavors(flavorlist);
            return dishDto;
        }).collect(Collectors.toList());
           //查询成功后缓存到redis中
         redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
